package com.yztc.xiami_app.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.liji.takephoto.TakePhoto;
import com.yztc.xiami_app.R;
import com.yztc.xiami_app.bean.user.MyUser;
import com.yztc.xiami_app.ui.activity.user.LoginActivity;
import com.yztc.xiami_app.ui.activity.user.PhoneRegisterActivity;
import com.yztc.xiami_app.ui.activity.user.RegisterActivity;
import com.yztc.xiami_app.ui.activity.user.SetActivity;
import com.yztc.xiami_app.ui.activity.user.UserInfoActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;

/**
 * A simple {@link Fragment} subclass.
 * “我的Fragment”
 */
public class MineFragment extends Fragment {
    @BindView(R.id.user_header_pic_iv)
    ImageView userHeaderPicIv; //用户头像
    @BindView(R.id.imageview_set_mine)
    ImageView mineSetIv; //我的设置
    @BindView(R.id.imageview_msg_mine)
    ImageView imageviewMsgMine;
    ImageView userInfoIv; //"查看用户个人信息"的图标
    @BindView(R.id.login_mine)
    Button loginBtn; //登录
    @BindView(R.id.regist_mine)
    Button registerBtn; //注册
    @BindView(R.id.layout_mine)
    RelativeLayout layoutMine;
    @BindView(R.id.toolbar2)
    Toolbar toolbar2;
    @BindView(R.id.textView)
    TextView loginStatus;


    private Context mContext;
    private PopupWindow mPopupWindow; //"选择注册方式"的PopupWindow


    public MineFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        //注册EventBus
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        mContext = getActivity();
        return view;
    }

    //关于"注册的PopUpWindow"的处理
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popUpView = inflater.inflate(R.layout.register_select_way, null, false);
        mPopupWindow = new PopupWindow(popUpView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setTouchable(true); //可以触摸,这句必须加，点击外部，才能取消
        //点击外部，可以取消
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.setOutsideTouchable(true);
        //设置PopupWindow的动画效果
        mPopupWindow.setAnimationStyle(R.style.anim_popUpWindow_bottom);


        TextView userNamePwdTv = (TextView) popUpView.findViewById(R.id.register_way_userName_pwd_tv); //用户名、密码注册
        TextView phoneTv = (TextView) popUpView.findViewById(R.id.register_way_phone_tv); //手机号码注册
        TextView cancelTv = (TextView) popUpView.findViewById(R.id.register_way_cancel);  //取消
        final Intent intent = new Intent();
        userNamePwdTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到"用户名、密码、邮箱"注册界面
                intent.setClass(mContext, RegisterActivity.class);
                startActivity(intent);
                mPopupWindow.dismiss(); //关闭PopupWindow
            }
        });
        phoneTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到"电话号码"注册界面
                intent.setClass(mContext, PhoneRegisterActivity.class);
                startActivity(intent);
                mPopupWindow.dismiss(); //关闭PopupWindow
            }
        });
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消，关闭PopupWindow
                mPopupWindow.dismiss();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解绑
        EventBus.getDefault().unregister(this);
    }

    //事件接收
    @Subscribe(sticky = true)
    public void onEvent(MyUser myUser) {
        BmobFile headerPicFile = myUser.getHeaderPic(); //用户头像在Bmob云的存储的文件
        //显示用户头像
        File saveFile = new File(Environment.getExternalStorageDirectory(), headerPicFile.getFilename());
        headerPicFile.download(saveFile, new DownloadFileListener() {
            @Override
            public void done(String savePath, BmobException e) {
                if (e == null) {
                    //显示用户头像
                    showUserHeader(savePath);
                    //设置登录状态
                    loginStatus.setText("已登录....");
                }
            }

            @Override
            public void onProgress(Integer integer, long l) {
            }
        });
    }

    //使用Mob注册
    private void register() {
        //打开注册页面
        RegisterPage registerPage = new RegisterPage();
        registerPage.setRegisterCallback(new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                // 解析注册结果
                if (result == SMSSDK.RESULT_COMPLETE) {
                    @SuppressWarnings("unchecked")
                    HashMap<String, Object> phoneMap = (HashMap<String, Object>) data;
                }
            }
        });
        registerPage.show(getActivity());
    }

    @OnClick({R.id.imageview_set_mine, R.id.imageview_msg_mine, R.id.layout_mine, R.id.login_mine,
            R.id.regist_mine, R.id.user_header_pic_iv})
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.imageview_set_mine:
                intent.setClass(mContext, SetActivity.class);
                startActivity(intent);
                break;
            case R.id.imageview_msg_mine:
                intent.setClass(mContext, UserInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.user_header_pic_iv:
                //用户头像
                final TakePhoto takePhoto = new TakePhoto(mContext);
                takePhoto.setOnPictureSelected(new TakePhoto.onPictureSelected() {
                    @Override
                    public void select(String path) {
                        //获取到的选择后的（无论是否剪裁），只要选择了照片，并点击了"确定"的按钮之后
                        //就会回调此方法，并回传图片的路径
                        //Log.i("tag","------->"+"选择的图片的地址:" + path);
                        //显示保存图片
                        showAndSavePic(path);
                    }
                });
                //显示选择的PopUpWindow
                takePhoto.show();
                break;
            case R.id.login_mine:
                //登录
                intent.setClass(mContext, LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.regist_mine:
                //注册
                //register();
                //显示供用户选择"注册方式"的PopupWindow
                mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    //显示并且保存图片
    private void showAndSavePic(String path) {
        showUserHeader("file://" + path);
        //把图片保存到Bmob云的文件管理
        final BmobFile bmobFile = new BmobFile(new File(path));
        //把图片的地址保存到Bmob云的用户管理的"_User"表中
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    //上传文件成功
                    Toast.makeText(mContext, "更换头像成功", Toast.LENGTH_SHORT).show();
                    //获取上传成功的文件的地址,并把该地址存储到"_User"表中
                    MyUser myUser = new MyUser();
                    myUser.setHeaderPic(bmobFile);
                    myUser.update("375d16bd1c", new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                //修改用户头像成功，已经保存在数据库的"_User"中
                            } else {
                                Log.i("tag", "----------->修改用户头像失败");
                            }
                        }
                    });
                } else {
                    Toast.makeText(mContext, "更换头像失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //显示用户头像
    private void showUserHeader(String path) {
        Glide.with(mContext).load(path)
                .asBitmap()
                .fitCenter()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                        roundedBitmapDrawable.setCircular(true); //设置圆形图片
                        userHeaderPicIv.setImageDrawable(roundedBitmapDrawable);
                    }
                });
    }

}
